package com.tsfyun.common.base.security;

import com.tsfyun.common.base.util.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;
import java.util.Optional;

/**
 * 登录工具类
 */
public class SecurityUtil {

    /**
     * 获取当前登录信息
     *
     * @return
     */
    public static LoginVO getCurrent() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.nonNull(authentication)) {
            //有可能取出来的是匿名
            return Optional.ofNullable(authentication.getPrincipal()).isPresent() &&  authentication.getPrincipal() instanceof LoginVO ?
                    (LoginVO) authentication.getPrincipal() : null;
        } else {
            return null;
        }
    }

    /**
     * 获取当前登录token
     *
     * @return
     */
    public static String getToken() {
        return Optional.ofNullable(getTokenVO()).map(r->r.getToken()).orElse(null);
    }

    public static TokenVO getTokenVO() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.nonNull(authentication)) {
            return Optional.ofNullable(authentication.getCredentials()).isPresent()
                    && authentication.getCredentials() instanceof TokenVO ? ((TokenVO) authentication.getCredentials()) : null;
        } else {
            return null;
        }
    }

    /**
     * 获取当前员工id/名称
     *
     * @return
     */
    public static String getCurrentPersonIdAndName() {
        return Optional.ofNullable(getCurrent()).map(r-> StringUtils.null2EmptyWithTrim(r.getPersonId()).concat("/").concat(StringUtils.null2EmptyWithTrim(r.getPersonName()))).orElse(null);
    }

    /**
     * =
     * 获取当前登录人员Id
     *
     * @return
     */
    public static Long getCurrentPersonId() {
        return Optional.ofNullable(getCurrent()).map(LoginVO::getPersonId).orElse(null);
    }

    /**
     * 获取当前登录人员的客户ID
     *
     * @return
     */
    public static Long getCurrentCustomerId() {
        return Optional.ofNullable( getCurrent()).map(LoginVO::getCustomerId).orElse(null);
    }

    /**
     * 获取当前登录人的客户名称
     * @return
     */
    public static String getCurrentCustomerName() {
        return Optional.ofNullable(getCurrent()).map(LoginVO::getCustomerName).orElse(null);
    }

    /**
     * =
     * 获取当前登录人员名称
     *
     * @return
     */
    public static String getCurrentPersonName() {
        return Optional.ofNullable(getCurrent()).map(LoginVO::getPersonName).orElse("");
    }


}
